﻿using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using Hxsoft.AppV1;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.Admin.RoleManage
{
	public partial class AddUsersToRole : BasePage
	{
		private LoadedValue<Guid> loadedIdentifier;
		public Guid Identifier
		{
			get
			{
				if (loadedIdentifier.Loader == null)
					loadedIdentifier.Loader = () => new Guid(Request.QueryString["RoleId"]);
				return loadedIdentifier.Value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if (!IsPostBack)
			{
				if (RightValidate())
					InitData();

				Page.DataBind();
			}
		}

		protected void BtSubmit_Click(object sender, EventArgs e)
		{
			if (RightValidate() && IsValid)
			{
				Roles.SetRoleUsers(Identifier, UCUser.SelectedItems.ToArray());
				OperateComplete();
			}
		}

		/// <summary>
		/// 初始化数据。
		/// </summary>
		public void InitData()
		{
			UCUser.SelectedItems.AddRange(Roles.GetUsersInRole(Identifier));
		}

		/// <summary>
		/// 返回权限验证结果，如果验证失败则显示消息提示。
		/// </summary>
		/// <returns>布尔值代表权限验证是否通过。</returns>
		public bool RightValidate()
		{
			bool right = Roles.RoleHasProperty(Identifier, Roles.RolePropertyCode.DisallowUserAccredit);
			if (right)
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.PermissionExceptionMessageTitle, Res.PermissionExceptionMessage));
				return !right;
			}

			right = Roles.GetAccreditRight(Roles.GetItem(Identifier));
			if (!right)
			{
				Messages.Add(new PageMessage(true, null, PageMessageType.Error, Res.PermissionExceptionMessageTitle, Res.PermissionExceptionMessage));
			}
			return right;
		}

		/// <summary>
		/// 授权操作完成，显示消息提示。
		/// </summary>
		public void OperateComplete()
		{
			Messages.Add(new PageMessage(true, null, PageMessageType.Prompt, Res.OperationCompleteTitle, Res.OperationComplete_RoleAccredit));
		}
	}
}
